import { Controller, Post, Body, Res } from '@nestjs/common';
import { LoginService } from './login.service';
import { CreateLoginDto } from './dto/create-login.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';

@ApiTags('登录')
@Controller('login')
export class LoginController {
  constructor(private readonly loginService: LoginService) {}
  @Post()
  @ApiOperation({
    summary: '登录',
    description: '传入userName和password',
  })
  async login(
    @Body() createLoginDto: CreateLoginDto,
    @Res({ passthrough: true }) response: Response,
  ) {
    const loginResult = await this.loginService.login(createLoginDto);
    // 如果登录成功，设置 Cookie
    if (loginResult.code === 200) {
      response.cookie('auth_token', loginResult.data.token, {
        httpOnly: true, // 防止XSS攻击
        secure: process.env.NODE_ENV === 'production', // 仅在HTTPS下传输
        maxAge: 24 * 60 * 60 * 1000, // 有效期24小时
        path: '/',
      });
    }
    return loginResult;
  }
}
